#include "../source/server.hpp"


// void HandleClose(Channel *channel){
//     DBG_LOG("close fd : %d", channel->fd());
//     // std::cout<< "close" << channel->fd() << std::endl;
//     channel->Remove();//移除监控
//     delete channel;
// }

// void HandleRead(Channel *channel){
//     int fd = channel->fd();
//     char buf[1024] = {0};
//     int ret = recv(fd, buf, 1023, 0);
//     if(ret <= 0){
//         HandleClose(channel);//关闭释放
//         return;
//     }
//     DBG_LOG("%s", buf);
//     // std::cout<< buf << std::endl;
//     channel->EnableWrite();//启动可写事件监控
// }

// void HandleWrite(Channel *channel){
//     int fd = channel->fd();
//     const char *data = "天气还不错";
//     int ret = send(fd, data, strlen(data), 0);
//     if(ret < 0){
//         return HandleClose(channel);
//     }
//     channel->DisableWrite();//关闭写监控
// }

// void HandleError(Channel *channel){
//     return HandleClose(channel);//关闭释放
// }

// void HandleEvent(EventLoop *loop, Channel *channel, uint64_t timerid){
//     loop->TimerRefresh(timerid);
// }


//管理所有的连接对象
std::unordered_map<uint64_t, PtrConnection> _conns;
uint64_t conn_id = 0;
EventLoop baseloop;
LoopThreadPool *loop_pool;

void ConnectionDestroy(const PtrConnection &conn){
    _conns.erase(conn->Id());
}
void OnConnected(const PtrConnection &conn){
    DBG_LOG("NEW CONNECTION:%p", conn.get());
}
void OnMessage(const PtrConnection &conn, Buffer *buf){
    DBG_LOG("%s",buf->ReadPosition());
    buf->MoveReadOffset(buf->ReadAbleSize());
    std::string str = "hello world!";
    conn->Send(str.c_str(), str.size());
    conn->Shutdown();
}
void NewConnection(int fd){
    conn_id++;
    PtrConnection conn(new Connection(loop_pool->NextLoop(), conn_id, fd));
    conn->SetMessageCallback(std::bind(OnMessage, std::placeholders::_1, std::placeholders::_2));//业务处理的回调函数
    conn->SetSrvCloseCallback(std::bind(ConnectionDestroy, std::placeholders::_1));//关闭事件的回调函数
    conn->SetConnectedCallback(std::bind(OnConnected, std::placeholders::_1));//连接建立完成回调函数
    //启动非活跃超时销毁
    conn->EnableInactiveRelease(10);
    conn->Established();//就绪初始化
    _conns.insert(std::make_pair(conn_id, conn));
    DBG_LOG("NEW---------------");
}

int main(){
    loop_pool = new LoopThreadPool(&baseloop);
    loop_pool->SetThreadCount(2);
    loop_pool->Create();
    Acceptor acceptor(&baseloop, 8080);
    //为监听套接字创建一个channel进行事件的管理，以及事件的处理
    acceptor.SetAcceptCallback(std::bind(NewConnection, std::placeholders::_1));//回调中，获取新连接，为新连接创建channel并且添加监控
    acceptor.Listen();
    baseloop.Start();
    return 0;
}